<template>
  <div class="out-container">
    <div class="search-container">
      <el-input placeholder="请输入内容" @keyup.enter.native="getFileByName" @clear="getclear" clearable v-model="queryParams.imgName" style="width: calc(100% - 96px);margin-right: 10px;">
        <template slot="prepend">
          <el-select v-model="queryParams.fileType" clearable placeholder="请选择" style="width: 100px;margin: -10px 0 0 -20px;">
            <el-option label="PSD" value="1" />
            <el-option label="TIF" value="2" />
            <el-option label="TIFF" value="3" />
            <el-option label="CDR" value="4" />
            <el-option label="AI" value="5" />
          </el-select>
          <el-input v-model="queryParams.imgType" placeholder="请输入文件分类" style="width: 120px;"></el-input>
        </template>
        <el-button slot="append" type="primary" icon="el-icon-camera-solid" @click="handleImportImage"></el-button>
      </el-input>
      <el-button type="primary" @click="getFileByName">搜一搜</el-button>
      <div class="identify" v-if="identifyShow" @click.stop>
        <el-upload
          class="upload-identify"
          ref="upload"
          :limit="1"
          accept=".png"
          :headers="upload.headers"
          :action="upload.url"
          :data="queryParams"
          :disabled="upload.isUploading"
          :on-success="handleImageSuccess"
          drag
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">拖拽图片到这里，或<em>点击上传</em></div>
        </el-upload>
        <el-upload
          class="upload-clack"
          ref="uploads"
          :headers="upload.headers"
          :action="upload.url"
          :data="queryParams"
          :disabled="upload.isUploading"
          :on-success="handleImageSuccess">
          <el-button size="small" type="primary">选择文件</el-button>
        </el-upload>
        <div class="identify-close" @click="identifyClose">
          <i class="el-icon-close"></i>
        </div>
      </div>
    </div>
    <div class="content-container">
      <div v-loading="loading" class="goods-container">
        <div v-for="(item, index) in paginatedData()" :key="index" :class="getSelectedCss(item.selected)">
          <el-image class="item-img" :src="`${item.bucketUrl}${item.imgPngPath}?t=${new Date().getTime()}`" :preview-src-list="[`${item.bucketUrl}${item.imgPngPath}?t=${new Date().getTime()}`]"></el-image>
          <div class="item-detail" @click="selectGoods(index)">
            <div class="list-item-title">{{ item.imgName }}</div>
            <div class="list-item-button-box">
              <el-button class="select-button" size="small" @click.stop="handleButtonClick(item, 'source')">源文件下载</el-button>
              <el-button class="select-button" size="small" @click.stop="handleButtonClick(item, 'jpeg')">jpeg下载</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <el-drawer title="下载进度" ref="drawer" :visible.sync="drawerOpen" :with-header="false" :modal="false" size="30%">
      <el-table :data="fileSelected">
        <el-table-column property="fileName" label="文件名称" align="center" show-overflow-tooltip />
        <el-table-column property="fileSize" label="大小" align="center" width="90">
          <template v-slot="scope">
            <span>{{ $fileSize(scope.row.fileSize) }}</span>
          </template>
        </el-table-column>
        <el-table-column property="progress" label="下载进度" align="center" width="300">
          <template slot="header">
            <div style="float: left;line-height: 35px;text-align: center;width: calc(100% - 30px);">下载进度</div>
            <el-tooltip class="item" effect="dark" content="清空已完成" placement="bottom">
              <el-button type="text" @click="deleteDoload()" icon="el-icon-delete-solid" style="float: right;color: red;font-size: 18px;"></el-button>
            </el-tooltip>
          </template>
          <template slot-scope="scope">
            <el-progress :percentage="scope.row.progress" :color="customColors" :status="scope.row.progressStatus" />
          </template>
        </el-table-column>
      </el-table>
    </el-drawer>

    <pagination
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="paginationChange"
    />
  </div>
</template>
<script lang="ts">
import { saveAs } from 'file-saver'
import { chunkDownloadFile } from '@/api/tool/minio'
import {getToken} from "@/utils/auth";
import { listImgInfo } from "@/api/business/imgInfo";

export default {
  name: "Login",
  computed: {
    test() {
      return test
    }
  },
  data() {
    return {
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 12,
        imgName: '',
        imgCategory: null,
        imgStatus: null,
        imgType:'',
      },
      // 遮罩层
      loading: false,
      // 总条数
      total: 0,
      goodsList:[],
      // 抽屉弹出
      drawerOpen: false,
      // 以图搜图抽屉弹出
      identifyShow: false,
      // true为以图搜图
      imageDataType: false,
      // 判断鼠标移出屏幕右侧
      isMouseInArea: false,
      // 选中图片列表
      fileSelected: [],
      drawerVal: 0,
      // 进度条颜色
      customColors: [
        {color: '#f56c6c', percentage: 20},
        {color: '#e6a23c', percentage: 40},
        {color: '#5cb87a', percentage: 60},
        {color: '#1989fa', percentage: 80},
        {color: '#6f7ad3', percentage: 100}
      ],
      // 用户导入参数
      upload: {
        // 弹出层标题（用户导入）
        title: "图片搜索",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/business/imgInfo/searchImage"
      },
    };
  },
  watch: {

  },
  created() {
    // this.getFileByName();
  },
  mounted() {
    /** 监听鼠标移动到了屏幕右侧30px的地方 */
    window.addEventListener('mousemove', this.handleMouseMove);
    document.addEventListener('click', this.handleOutsideClick);
  },
  beforeDestroy() {
    /** 移除监听鼠标移动到了屏幕右侧30px的地方 */
    window.removeEventListener('mousemove', this.handleMouseMove);
    document.removeEventListener('click', this.handleOutsideClick);
  },
  methods: {
    paginationChange(){
      if (!this.imageDataType){
        this.getFileByName()
      }
    },
    // 计算当前页的数据
    paginatedData() {
      if (!this.imageDataType){
        return this.goodsList
      }else {
        const start = (this.queryParams.pageNum - 1) * this.queryParams.pageSize;
        const end = start + this.queryParams.pageSize;
        return this.goodsList.slice(start, end);
      }
    },
    getclear(){
      this.goodsList = [];
      this.total = 0;
    },
    getFileByName() {
      this.loading = true;
      listImgInfo(this.queryParams).then(response => {
        this.goodsList = response.rows;
        this.imageDataType = false
        this.total = response.total;
        this.loading = false;
      });
    },
    getSelectedCss(selected){
      if(selected == true){
        return 'goods-item selected';
      }else{
        return 'goods-item';
      }
    },
    selectGoods(id){
      let newGoods = Object.assign({}, this.goodsList[id]);
      newGoods.selected = !newGoods.selected;
      this.$set(this.goodsList, id, newGoods);
    },
    // 以图搜图方法
    handleImportImage(){
      this.identifyShow = true
    },
    identifyClose(){
      this.identifyShow = false
    },
    handleOutsideClick(event) {
      if (!this.$el.contains(event.target)) {
        this.identifyShow = false;
      }
    },
    // 图片上传完毕关闭窗口
    handleImageSuccess(res,file, fileList){
      const msg = JSON.parse(res.msg)
      this.$refs.upload.clearFiles();
      this.$refs.uploads.clearFiles();
      this.identifyShow = false;
      this.goodsList = msg.data.map(item => item.content)
      this.imageDataType = true
      this.total = msg.data.length;
    },
    /** 鼠标滑过抽屉弹出 */
    mouseover(){
      this.drawerOpen = !this.drawerOpen
      this.drawerVal++
    },
    /** 清空已下载完成 */
    deleteDoload(){
      this.fileSelected = this.fileSelected.filter(i => i.progress != 100)
    },
    // 监听鼠标移动到了屏幕右侧30px的地方
    handleMouseMove(event) {
      // 检查鼠标X坐标是否大于屏幕宽度减去30px
      if (event.clientX > window.innerWidth - 30) {
        this.drawerOpen = true
      }
      if (event.clientX < window.innerWidth - window.innerWidth * 0.3) {
        // 如果鼠标之前在区域内，现在移出了区域
        if (this.isMouseInArea) {
          this.isMouseInArea = false;
          this.drawerOpen = false
        } else {
          if (!this.isMouseInArea) {
            this.isMouseInArea = true;
          }
        }
      }
    },
    /** 下载jpeg和psd */
    handleButtonClick(e, type){
      const createFileObject = (item, extension, pathKey, sizeKey, replaceExtension = true) => ({
        fileName: replaceExtension ? `${item.imgName.replace(/\.[^.]*$/, '')}.${extension}` : item.imgName,
        filePath: item[pathKey],
        fileSize: item[sizeKey],
        progress: 0,
        progressStatus: undefined,
        complete: false, // 是否完成
      });
      if (type == 'source'){
        this.fileSelected.push(createFileObject(e, 'source', 'imgSourcePath', 'imgSourceSize', false));
      }else if (type == 'jpeg'){
        this.fileSelected.push(createFileObject(e, 'jpg', 'imgJpgPath', 'imgJpgSize'));
      }
      // this.drawerOpen = true
      this.downloadSelectedFiles(this.fileSelected);
    },
    /** 下载选中的文件 */
    async downloadSelectedFiles() {
      const CHUNK_SIZE = 1024 * 1024 * 5
      // 遍历选中的，带着index序号
      for (const item of this.fileSelected) {
        if (!item.complete){
          item.complete = true
          // 计算分片数量
          const totalChunks = Math.ceil(item.fileSize / CHUNK_SIZE);
          const offset =  0;
          const chunks = [];
          for (let i = offset + 1; i <= totalChunks; i++) {
            const start = CHUNK_SIZE * (i - 1);
            let end = CHUNK_SIZE * i - 1;
            if (end > item.fileSize ) {
              end = item.fileSize;
            }
            const res = await chunkDownloadFile(item, `bytes=${start}-${end}`);
            chunks.push(res);
            // 更新进度条进度
            const progress = Math.round((i / totalChunks) * 100);
            this.$set(item, 'progress', progress);
            if (progress === 100) {
              this.$set(item, 'progressStatus', 'success');
            }
          }
          const blob = new Blob(chunks, { type: 'application/octet-stream' });
          this.getsaveAs(blob, decodeURIComponent(item.fileName))
        }
      }
    },
    getsaveAs(text, name, opts) {
      saveAs(text, name, opts);
    },
  }
};
</script>

<style lang="postcss" scoped>
/deep/ .el-image__inner{
  object-fit: contain !important;
}
/deep/ .el-input-group > .el-input__inner{
  height: 30px !important;
}
.upload-identify /deep/ .el-upload{
  width: 100%;
  height: 100px;
}
.upload-identify /deep/ .el-upload-dragger{
  width: 100%;
  height: 100px;
}
.upload-identify /deep/ .el-icon-upload{
  display: none;
}
.upload-identify /deep/ .el-upload__text{
  line-height: 100px;
}
</style>
<style rel="stylesheet/scss" lang="scss" scoped>
  .out-container{
    display: flex;
    flex-direction: column;

  }

  .search-container{
    margin-top: calc(10px + 2%);
    //margin-bottom: calc(10px + 2%);
    padding: 0 15% 0 15%;
  }

  .content-container{
    display: flex;
    flex-direction: column;
    font-size: 12px;
    color: var(--Ga10);
    font-family: Microsoft Yahei,Hiragino Sans GB,Heiti SC,WenQuanYi Micro Hei,sans-serif !important;
  }

  ::v-deep .el-input-group__prepend{
    padding-right: 2px!important;
  }

  .goods-container {
    display: flex;
    flex-direction: row;
    justify-content: flex-start; /* 更改 'left' 为 'flex-start' 以获得更好的兼容性 */
    flex-wrap: wrap; /* 允许子项换行 */
    padding-left: 25px;
  }

  .goods-item {
    box-shadow: 0 12px 20px 0 rgba(0,0,0,.1);
    cursor: pointer;
    display: flex;
    position: relative;
    margin-top: 40px;
    margin-right: 40px; /* 每个元素之间的间距 */
    width: calc(25% - 40px); /* 4个元素的宽度，减去右边距 */
    height: 185px;
    background: var(--Wh0);
    border-radius: 8px;
    border: 1.5px transparent solid;
    transition: transform .2s;
  }

  /* 确保每行有4个元素后，最后一个元素没有右边距 */
  .goods-item:nth-child(4n) {
    margin-right: 0;
  }


  .selected{
    border: 1.5px #00afff solid;
    box-shadow: 0 12px 20px 0 rgba(0,0,0,.1);
  }

  .item-img {
    transition: transform .1s;
    background: var(--Wh0);
    box-shadow: 3px 3px 2px 0 rgba(0,0,0,.1);
    border-radius: 8px;
    left: 20px;
    bottom: 24px;
    position: absolute;
    width: 30%;
    height: 175px;
    background-repeat: no-repeat;
    background-size: 100% 100%;
  }

  .item-detail{
    margin-left: 40%;
  }

  .list-item-title{
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    margin-top: 30px;
    width: 100%;
    height: 48px;
    font-size: 18px;
    color: var(--Ga10);
    letter-spacing: 0;
    line-height: 24px;
  }

.list-item-button-box{
  padding-right: 25px;
  margin-top: 40px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}


  .select-button{
    border-radius: 5px;/** 圆角外框  */
    border: 1px solid rgb(0, 174, 236);
    background-color: rgb(0, 174, 236);
    color: #FFFFFF;
  }

  .select-button:hover{
    filter: brightness(1.2);
  }

  .identify{
    width: calc(68% + 15px);
    box-shadow: 0 2px 10px 0 rgba(0, 0, 0, .1);
    margin-top: 10px;
    padding: 20px 20px 0 20px;
    border-radius: 10px;
    position: absolute;
    z-index: 999;
    background: #FFF;
  }

  .upload-clack{
    text-align: center;
    margin-top: 10px;
  }
  .identify-close{
    height: 20px;
    float: right;
    width: 18px;
    cursor: pointer;
    text-align: center;
  }
</style>

